﻿/* ËùÔÚÄ£¿é£º¹«¹²´¦ÀíÀàÂß¼­²ã
* ÎÄ¼þ¹¦ÄÜ£º¹«¹²´¦ÀíÀà
* ×÷Õß£ºÑàÇì
* ´´½¨Ê±¼ä£º2009-08-15 
*/
using System;
using System.Collections.Specialized;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;

namespace OF.Utility
{
    public static class EConvert
    {
        private static readonly Regex INTEGER_REGEX = new Regex(@"^\-?\d{1,9}$", RegexOptions.Compiled);
        private static readonly Regex LONG_REGEX = new Regex(@"^\-?\d{1,18}$", RegexOptions.Compiled);
        private static readonly Regex SHORT_REGEX = new Regex(@"^\-?\d{1,5}$", RegexOptions.Compiled);
        private static readonly Regex FLOAT_REGEX = new Regex(@"^\-?\d+(\.\d+)?$", RegexOptions.Compiled);

        public static string ToString(object data, string def_value)
        {
            if (data == null || data == DBNull.Value)
                return def_value;

            return Convert.ToString(data).Trim();
        }
        public static string ToString(object data)
        {
            return ToString(data, string.Empty);
        }
        public static string ToString(TextBox ctrl)
        {
            return ToString(ctrl.Text.Trim(), string.Empty);
        }
        public static int ToInt(object data, int def_value)
        {
            if (data == null || data == DBNull.Value)
                return def_value;

            if (data is int)
                return (int)data;

            if (INTEGER_REGEX.IsMatch(data.ToString()))
            {
                return Convert.ToInt32(data);
            }
            else
            {
                try
                {
                    return Convert.ToInt32(data);
                }
                catch
                {
                    return def_value;
                }
            }
        }
        public static int ToInt(object data)
        {
            return ToInt(data, 0);
        }

        public static long ToLong(object data)
        {
            if (data == null || data == DBNull.Value)
                return 0L;

            if (data is long)
                return (long)data;

            if (LONG_REGEX.IsMatch(data.ToString()))
            {
                return Convert.ToInt64(data);
            }
            else
            {
                try
                {
                    return Convert.ToInt32(data);
                }
                catch
                {
                    return 0L;
                }
            }
        }

        public static short ToShort(object data)
        {
            if (data == null || data == DBNull.Value)
                return 0;

            if (data is short)
                return (short)data;

            if (SHORT_REGEX.IsMatch(data.ToString()))
            {
                return Convert.ToInt16(data);
            }
            else
            {
                try
                {
                    return Convert.ToInt16(data);
                }
                catch
                {
                    return 0;
                }
            }
        }

        public static DateTime ToDateTime(object data)
        {
            return ToDateTime(data, Convert.ToDateTime("1900-01-01"));
        }
        public static DateTime ToDateTime(object data, DateTime def_value)
        {
            if (data == null || data == DBNull.Value)
                return def_value;

            if (data is DateTime)
                return (DateTime)data;

            try
            {
                return Convert.ToDateTime(data);
            }
            catch
            {
                return def_value;
            }
        }
        /// <summary>
        ///  转换成时间格式的字符串，可提供默认值
        /// </summary>
        /// <param name="data">各种类型的时间</param>
        /// <param name="fmt">时间字符串格式化，例如 yyyy-MM-dd</param>
        /// <param name="def_value">为null时返回默认字符串</param>
        /// <returns></returns>
        public static string ToDateTimeStr(object data, string fmt, string def_value)
        {

            if (data == null || data == DBNull.Value)
                return def_value;
            if (data is DateTime)
            {
                DateTime time = (DateTime)data;
                return time.ToString(fmt);
            }
            try
            {
                return Convert.ToDateTime(data).ToString(fmt);
            }
            catch
            {
                return def_value;
            }
        }
        public static decimal ToDecimal(object data)
        {
            if (data == null || data == DBNull.Value)
                return 0;

            if (data is decimal)
                return (decimal)data;

            try
            {
                return Convert.ToDecimal(data);
            }
            catch
            {
                return 0;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static decimal ToDecimal(object data, decimal defaultValue)
        {

            if (data is decimal)
                return (decimal)data;

            try
            {
                return Convert.ToDecimal(data);
            }
            catch
            {
                return defaultValue;
            }
        }
        public static bool ToBoolean(object d)
        {
            return ToBoolean(d, false);
        }
        public static bool ToBoolean(object d, bool def_value)
        {
            if (d == null || d == DBNull.Value)
                return def_value;

            if (d is bool)
                return (bool)d;

            try
            {
                return Convert.ToBoolean(d);
            }
            catch
            {
                return def_value;
            }
        }

        public static byte ToByte(object data)
        {
            if (data == null || data == DBNull.Value)
                return 0;

            if (data is byte)
                return (byte)data;

            try
            {
                return Convert.ToByte(data);
            }
            catch
            {
                return 0;
            }
        }

        public static byte[] ToBinary(object data)
        {
            try
            {
                return (byte[])data;
            }
            catch
            {
                return null;
            }
        }
        public static float ToFloat(object data)
        {
            if (data == null || data == DBNull.Value)
                return 0f;

            if (data is float)
                return (float)data;

            if (FLOAT_REGEX.IsMatch(data.ToString()))
            {
                return Convert.ToSingle(data);
            }
            else
            {
                return 0f;
            }
        }

        public static string ToBase64(string strnormal)
        {
            try
            {
                return Convert.ToBase64String(Encoding.Default.GetBytes(strnormal));
            }
            catch
            {
                return string.Empty;
            }
        }
        public static string FromBase64(string strbase64)
        {
            try
            {
                return Encoding.Default.GetString(Convert.FromBase64String(strbase64));
            }
            catch
            {
                return string.Empty;
            }
        }
        /// <summary>
        /// ½âÂë
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string URLDecode(string str)
        {
            return System.Web.HttpUtility.UrlDecode(str, Encoding.UTF8).Replace("\"", "&quot;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("'", "%27");
        }
        /// <summary>
        /// ±àÂë
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string URLEncode(string str)
        {
            return System.Web.HttpUtility.UrlEncode(str, Encoding.UTF8).Replace("'", "%27"); ;
        }

        /// <summary>
        /// °üÀ¨ÌØÊâ sql ½Å±¾
        /// </summary>
        /// <returns></returns>
        public static bool CheckContainsSqlCommand(NameValueCollection QueryString)
        {
            string SqlCommandString = "or |and |exec |insert |select |delete |update |count |* |chr |mid |master |truncate |char |declare ";
            string[] SqlCommandArr = SqlCommandString.Split('|');
            for (int k = 0; k < QueryString.Count; k++)
            {
                for (int i = 0; i < SqlCommandArr.Length; i++)
                {
                    if (QueryString[k].IndexOf(SqlCommandArr[i]) >= 0)
                    {
                        return true;
                    }
                }
            }
            //foreach (KeyValuePair<string, string> kvp in QueryString)
            //{
            //}
            return false;
        }
        
        /// <summary>
        /// 日期 yyyy-MM-dd HH:mm
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static string FormatDateTime(string val)
        {
            DateTime time;
            if (string.IsNullOrEmpty(val) || !DateTime.TryParse(val, out time))
                return string.Empty;

            return time.ToString("yyyy-MM-dd HH:mm");
        }

        /// <summary>
        /// 日期 
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static string FormatDateTime(DateTime? time)
        {
            if (Equals(null, time))
                return string.Empty;

            return time.Value.ToString("yyyy-MM-dd HH:mm");
        }

        /// <summary>
        /// 日期 
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static string FormatDateTime(DateTime time)
        {
            return time.ToString("yyyy-MM-dd HH:mm");
        }



    }
}
